﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Xml;
using Exam.Core;
using Exam.Core.DBUtility;
using Exam.Core.DAL;

public partial class Student_Service_exam : StudentPageBase {

    string paperid = "";
    string myid = "";
    string SEId = "";  //考生考卷ID
    JArray paper = new JArray();
    Dictionary<string, string> _dictionary = new Dictionary<string,string>(); //存储考生答案

    Exam.Core.DAL.Paper dal = new Exam.Core.DAL.Paper();

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            Thread.Sleep(3);
            string requestJson = string.Empty;
            using (StreamReader reader = new StreamReader(Context.Request.InputStream)) {
                requestJson = reader.ReadToEnd();//获取传递过来的考生答案

            }

            write(requestJson);

            //获取考卷信息 题型 分值


            JObject o = JObject.Parse(requestJson);
            //考卷
            paper = (JArray)o["paper"];
            //试卷ID
            paperid = (string)o["paperid"];
            //获取考卷路径
            string paperfilepath = (string)o["paperfilepath"];
            //题型列表
            string typelist = (string)o["typelist"];
            //考生ID
            myid = (string)o["myid"];
            //保存考生成绩ID
            SEId = (string)o["SEId"];

            //计算试卷总分
            double totalscore = 0;

            //保存考生得分
            double studenttotalscore = 0;

            //获取考卷内容
            List<Exam.Core.Model.ExamQuestionType> paperlist = dal.getExamQType(paperfilepath);

            string stuexamxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><content>";

            for (int n = 0; n < paperlist.Count; n++) {//遍历题型

                //开始题型
                string strtype = "<questiontype id=\"" + paperlist[n].QuestionTypeId.Trim() +
                    "\" score=\"" + paperlist[n].Score.Trim() + "\">";

                for (int i = 0; i < paper.Count; i++) {
                    string tmp = paper[i].ToString();
                    JObject o1 = JObject.Parse(tmp);
                    IEnumerable<JProperty> properties = o1.Properties();
                    foreach (JProperty item in properties) {
                        //Console.WriteLine(item.Name + ":" + item.Value);
                        //JArray paper1 = (JArray)o1[item.Name];
                        string _name = item.Name;
                        string _value = item.Value.ToString();
                        _dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(_value);

                        //通过键的集合取
                        foreach (string key in _dictionary.Keys) {
                            //Console.WriteLine(key + _dictionary[key]);
                            string[] qnumber = key.Split('_');//题号
                            string qanswer = _dictionary[key];//考生答案 明天继续

                            string typeid = qnumber[0];
                            string questionid = qnumber[1];

                            //将考生答案写入考生提交试卷XML文件
                            Exam.Core.Model.ExamQuestionType objtype = paperlist[n];

                            
                            if (typeid.Trim() == objtype.QuestionTypeId.Trim()) {//判断题型是否正确题型

                                //判断试题编号是否正确
                                //循环题目列表
                                for (int j = 0; j < objtype.QuestionList.Count; j++) {
                                    //找到该题式
                                    if (questionid.Trim() == objtype.QuestionList[j].QuestionId.Trim()) {

                                        //计算该试卷总分
                                        totalscore =  totalscore + double.Parse(paperlist[n].Score.Trim());

                                        StringBuilder sb1 = new StringBuilder();
                                        string stuscore = "0";
                                        //判断考生答案 是否与正确答案一致
                                        if (qanswer.ToUpper().Trim() == objtype.QuestionList[j].QuestionAnswer.ToUpper().Trim()) {
                                            //给分
                                            stuscore = objtype.Score.Trim();
                                            studenttotalscore = studenttotalscore + double.Parse(stuscore);
                                        }
                                        sb1.Append("<question questionid=\"" + questionid.Trim() + "\" answer=\"" + objtype.QuestionList[j].QuestionAnswer.ToUpper().Trim() + "\" studentanswer=\"" + qanswer.ToUpper().Trim() + "\" stuscore=\"" + stuscore + "\" />");
                                        strtype += sb1.ToString().Trim(); 
                                    }
                                    
                                }

                                
                                
                            }
                             

                        }
                    }

                }
                //闭合题型
                strtype += "</questiontype>";
                //闭合XML
                stuexamxml += strtype;

            }
            stuexamxml += "</content></root>";

            



            //保存考生考卷为XML文件StuExam
            string studentpaperfile =  paperid+ "_" + myid + ".xml";
            writexml(stuexamxml, studentpaperfile);

            double studenttotalscorepercent = (studenttotalscore/totalscore)*100;//百分制得分

            string _papertotal = String.Format("{0:F}", totalscore);//
            string _studenttotal = String.Format("{0:F}",studenttotalscore);//默认为保留两位;
            string _studenttotalpercent =  String.Format("{0:F}",studenttotalscorepercent);

            //交卷
            //计算得分
            //保存数据库
            //StudentId PaperId
            //将考生考卷关联表 StudentPaper 试卷状态字段更新
            string SQL = "UPDATE StudentPaper SET PaperStatus=2 WHERE StudentID=" + myid + " AND PaperID=" + paperid;
            bool result = dal.ExecuteSql(SQL);
            if (result) {
                SQL = "UPDATE StudentExam SET EndTime='" + DateTime.Now.ToString() +
                    "', StudentPaper='" + studentpaperfile +
                    "', PaperTotal=" + _papertotal +
                    ", TotalScore=" + _studenttotal +
                    ", TotalScorePer=" + _studenttotalpercent +
                    ", ExamStatus=2, NeedRead=0 WHERE StudentExamId=" + SEId;

                result = dal.ExecuteSql(SQL);

                if (result) {
                    Response.Write("1");
                }
                else {//没写进去要回滚数据
                    SQL = "UPDATE StudentExam SET EndTime='" + DateTime.Now.ToString() +
                    "', StudentPaper='" + 0 +
                    "', TotalScore=" + 0 +
                    ", TotalScorePer=" + 0 +
                    ", ExamStatus=1, NeedRead=0 WHERE StudentExamId=" + SEId;

                    result = dal.ExecuteSql(SQL);
                    Response.Write("0");
                }
            }
            else {//没写进去要回滚数据
                SQL = "UPDATE StudentPaper SET PaperStatus=1 WHERE StudentID=" + myid + " AND PaperID=" + paperid;
                result = dal.ExecuteSql(SQL);
            }

            Response.End();
        }
    }

    private void writexml(string stuexamxml,string studentpaperfile) {
        //写入xml
        string strXML = stuexamxml;
        string strFolder = FilePath.StuExamPath.Trim(); // +"_" + seid;
        if (!System.IO.Directory.Exists(strFolder)) {
            System.IO.Directory.CreateDirectory(strFolder);
        }
        string strFileName = strFolder + studentpaperfile;
        string file = strFileName;
        using (StreamWriter streamw = File.CreateText(file)) {
            streamw.Write(strXML);
        }
    }

    private void write(string str) {
        string file = Server.MapPath("a.txt");
        using (StreamWriter streamw = File.CreateText(file)) {
            streamw.Write(str);
        }
    }

    //返回某一个题型
    private Exam.Core.Model.ExamQuestionType findExamQuestionType(List<Exam.Core.Model.ExamQuestionType> _eqt,string _v ) {
        Exam.Core.Model.ExamQuestionType  tmp =
            _eqt.Find(delegate(Exam.Core.Model.ExamQuestionType v) { return v.QuestionTypeId== _v; });
        return tmp;

    }

    /**

    private string SaveStuExam(){

        XmlText xmltext;
        XmlDocument xmldoc = new XmlDocument();
        XmlNode xmlnode = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
        xmldoc.AppendChild(xmlnode);

        XmlElement root = xmldoc.CreateElement("", "root", "");
        xmltext = xmldoc.CreateTextNode("");
        root.AppendChild(xmltext);
        xmldoc.AppendChild(root);

        XmlElement content = xmldoc.CreateElement("", "content", "");
        xmltext = xmldoc.CreateTextNode("");
        content.AppendChild(xmltext);
        xmldoc.ChildNodes.Item(1).AppendChild(content);

        for (int i = 0; i < 10; i++) {
            string[] tmpType = questionType[i].Trim('_').Split('_');

            XmlElement questiontype = xmldoc.CreateElement("", "questiontype", "");
            xmltext = xmldoc.CreateTextNode("");
            questiontype.AppendChild(xmltext);
            questiontype.SetAttribute("id", "", tmpType[0].Trim());
            questiontype.SetAttribute("score", tmpType[1].Trim());
            xmldoc.ChildNodes.Item(1).AppendChild(content).AppendChild(questiontype);


            XmlElement questiontype1 = xmldoc.CreateElement("", "questiontype", "");
            xmltext = xmldoc.CreateTextNode("");
            questiontype1.AppendChild(xmltext);
            questiontype1.SetAttribute("id", "", tmpType[0].Trim());
            questiontype1.SetAttribute("score", tmpType[1].Trim());
           


            List<String> SQLStringList = new List<String>();
            #endregion
            

            XmlElement questionid = xmldoc.CreateElement("", "questionid", "");
            xmltext = xmldoc.CreateTextNode("");
            questionid.AppendChild(xmltext);
            questionid.InnerText = ids.Trim();
            xmldoc.ChildNodes.Item(1).AppendChild(content).AppendChild(questiontype).AppendChild(questionid);

            SQLStringList.Clear();

        }

        string paperFileName = DateTime.Now.ToString("yyyyMMddhhmmss").Trim() + ".xml";
        string path = FilePath.StuExamPath.Trim() + paperFileName;
        if (!File.Exists(path)) {
            File.Delete(path);
        }
        xmldoc.Save(path); //保存
    }


    **/



}
